package cn.yunyichina.provider.bone.service.impl;

import cn.yunyichina.provider.bone.dao.UserVisitDao;
import cn.yunyichina.provider.bone.dao.UserVisitListDao;
import cn.yunyichina.provider.bone.entity.UserVisit;
import cn.yunyichina.provider.bone.entity.UserVisitList;
import cn.yunyichina.provider.bone.utils.BoneMsgUtils;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.MessageService;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by zhuxp on 2017/12/5.
 *
 * @param
 * @Descrition
 */
@Service
public class UserVisitServiceImpl {

    private SimpleDateFormat simpleDateFormat  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static Logger logger = LoggerFactory.getLogger(VisitTemplateServiceImpl.class);

    private final String USER_VISIT_APP_CODE ="yyt48fe49dbe6eb1ceb";
    private final String USER_VISIT_TEMPLATECODE ="TMP33001";

    @Autowired
    private UserVisitDao userVisitDao;
    @Autowired
    private UserVisitListDao userVisitListDao;

    /**
     * yyt.bone.user.visit.list
     * 查询患者随访记录列表
     * @param data
     * @return
     */
    public Response listUserVisit(String data){
        logger.info("查询患者随访记录列表 listUserVisit请求入参:"+data);
        Response response = new Response();
        try {
            UserVisit userVisit = JsonUtils.parseObject(data, UserVisit.class);
            if(StringUtils.isBlank(userVisit.getDoctorId())){
                response.setResultCodeAndMessage("-2","医生id不能为空!");
                return response;
            }
            List<UserVisit> userVisits = userVisitDao.queryUserVisitList(userVisit);
            logger.info("查询患者随访记录列表,请求listUserVisit出参:"+JsonUtils.toJsonString(userVisits));
            response.setResultCodeAndMessageAndResult("0","查询患者随访记录列表成功!",JsonUtils.toJsonString(userVisits));
        }catch (Exception e){
            logger.error("查询患者随访记录列表异常!",e);
            response.setResultCodeAndMessage("-1","查询患者随访记录列表异常!");
        }
        return response;
    }

    /**
     * yyt.bone.user.visit.insert
     * 新增患者随访记录列表
     * @param data
     * @return
     */
    public Response insertUserVisit(String data){
        logger.info("新增患者随访记录 请求insertUserVisit入参:"+data);
        Response response = new Response();
        try {
            UserVisit userVisit = JsonUtils.parseObject(data,UserVisit.class);
            if(StringUtils.isBlank(userVisit.getUserId())||StringUtils.isBlank(userVisit.getDoctorId())){
                response.setResultCodeAndMessage("-2","用户id或医生Id不能为空!");
                return response;
            }
            if(StringUtils.isBlank(userVisit.getPersonalOpenId())){
                response.setResultCodeAndMessage("-2","用户openId不能为空!");
                return response;
            }
            //查看该医生的这个患者 是否有未完成的随访记录  ---  begin
            UserVisit uv = new UserVisit();
            uv.setDoctorId(userVisit.getDoctorId());
            uv.setUserId(userVisit.getUserId());
            uv.setStatus((short) 0);
            List<UserVisit> uvs = userVisitDao.select(uv);
//            boolean flag = true;
//            for(UserVisit userVisit1:uvs){
//                if(userVisit1.getStatus()==0){
//                    flag=false;
//                    break;
//                }
//            }
            if (uvs.size()>0){
                response.setResultCodeAndMessage("-2","该患者存在未完成的随访记录，新增失败！");
                return response;
            }
            //查看该医生的这个患者 是否有未完成的随访记录  ---  end------------------

            JSONObject jsonObject = JSONObject.parseObject(data);
            Object obj = jsonObject.get("visit_lists");
            if(obj ==null){
                response.setResultCodeAndMessage("-2","患者随访明细不能为空!");
                return response;
            }
            userVisit.setId(PKGenerator.generateId());
            userVisit.setUpdateTime(simpleDateFormat.format(new Date()));
            userVisit.setCreateTime(simpleDateFormat.format(new Date()));
            //初始状态设置为 0 （0：待完成 1：已完成 2：已终止）
            userVisit.setStatus((short) 0);

            List<UserVisitList> userVisitLists = JsonUtils.parseArray(obj.toString(),UserVisitList.class);
            for (UserVisitList entity:userVisitLists){
                entity.setId(PKGenerator.generateId());
                entity.setVisitId(userVisit.getId());
                entity.setVisitName(userVisit.getVisitTemplateName());
                entity.setCreateTime(userVisit.getCreateTime());
                entity.setUpdateTime(userVisit.getUpdateTime());
                //初始状态设置为 0 待完成
                entity.setStatus((double) 0);
                userVisitListDao.insert(entity);
            }
            userVisitDao.insert(userVisit);
        }catch (Exception e){
            logger.error("新增患者随访记录异常!",e);
            response.setResultCodeAndMessage("-1","新增患者记录异常!");
        }
        return response;
    }

    /**
     * yyt.bone.user.visit.terminate
     * 终止患者随访
     * @param data
     * @return
     */
    public Response terminateUserVisit(String data){
        logger.info("更新患者随访记录 请求updateUserVisitStatus入参:"+data);
        Response response = new Response();
        try {
            UserVisit userVisit = JsonUtils.parseObject(data,UserVisit.class);
            if(StringUtils.isBlank(userVisit.getId())){
                response.setResultCodeAndMessage("-2","随访记录id不能为空!");
                return response;
            }
            UserVisit entity = userVisitDao.selectById(userVisit.getId());
            if(entity.getStatus()!=0){
                response.setResultCodeAndMessage("-2","随访记录状态不正常!");
                return response;
            }
            UserVisitList userVisitList = new UserVisitList();
            userVisitList.setVisitId(entity.getId());
            List<UserVisitList> userVisitLists = userVisitListDao.select(userVisitList);
            //随访记录明细状态更新成已终止
            for(UserVisitList uvl:userVisitLists){
                //未推送的随访明细 更新状态为 已终止  0：待完成  1：已完成  2：已终止
                if(uvl.getStatus()==0){
                    uvl.setStatus((double) 2);
                    uvl.setUpdateTime(simpleDateFormat.format(new Date()));
                    userVisitListDao.update(uvl);
                }
            }
            //随访记录状态更新为已终止
            entity.setStatus((short) 2);
            entity.setUpdateTime(simpleDateFormat.format(new Date()));
            userVisitDao.update(entity);
        }catch (Exception e){
            logger.error("更新患者随访记录异常!",e);
            response.setResultCodeAndMessage("-1","更新患者记录异常!");
        }
        return response;
    }

    /**
     * yyt.bone.user.visit.delete
     * 删除患者随访记录列表
     * @param data
     * @return
     */
    public Response deleteUserVisit(String data){
        logger.info("删除患者随访记录 请求deleteUserVisit入参:"+data);
        Response response = new Response();
        try {
            UserVisit userVisit = JsonUtils.parseObject(data,UserVisit.class);
            if(StringUtils.isBlank(userVisit.getId())){
                response.setResultCodeAndMessage("-2","患者随访记录id不能为空!");
                return response;
            }
            UserVisit entity = userVisitDao.selectById(userVisit.getId());
            if(entity==null){
                response.setResultCodeAndMessage("-2","患者随访记录不存在!");
                return response;
            }
            //删除随访明细
            UserVisitList userVisitList = new UserVisitList();
            userVisitList.setVisitId(entity.getId());
            List<UserVisitList> userVisitLists = userVisitListDao.select(userVisitList);
            for(UserVisitList uvl:userVisitLists){
                userVisitListDao.delete(uvl);
            }
            //删除随访记录
            userVisitDao.delete(entity);
            response.setResultCodeAndMessage("0","删除随访记录成功!");
        }catch (Exception e){
            logger.error("删除患者随访记录异常!",e);
            response.setResultCodeAndMessage("-1","删除患者记录异常!");
        }
        return response;
    }
    /**
     * yyt.bone.user.visit.detail.list
     * @descreption 获取随访明细列表
     * 用于定时任务  获取明细列表
     * @param data
     * @return
     */
    public Response listUserVisitDetail(String data){
        logger.info("获取随访明细列表,请求listUserVisitDetail入参:"+data);
        Response response = new Response();
        try {
            UserVisitList userVisitList = JsonUtils.parseObject(data,UserVisitList.class);
            List<UserVisitList> userVisitLists = userVisitListDao.select(userVisitList);
            if(userVisitLists.isEmpty()){
                response.setResultCodeAndMessage("-2","满足条件的随访明细不存在!");
                return response;
            }
            logger.info("获取随访明细列表,请求listUserVisitDetail出参:"+JsonUtils.toJsonString(userVisitLists));
            response.setResultCodeAndMessageAndResult("0","查询随访明细列表成功!",JsonUtils.toJsonString(userVisitLists));
        }catch (Exception e){
            logger.error("获取随访明细列表异常!",e);
            response.setResultCodeAndMessage("-1","获取随访明细列表异常!");
        }
        return response;
    }

    /**
     * yyt.bone.user.visit.detail.query
     * @descreption 获取单条随访明细
     * 获取单条
     * @param data
     * @return
     */
    public Response queryUserVisitDetail(String data){
        logger.info("获取随访明细,请求queryUserVisitDetail入参:"+data);
        Response response = new Response();
        try {
            UserVisitList userVisitList = JsonUtils.parseObject(data,UserVisitList.class);
            UserVisitList returnVisit =userVisitListDao.selectById(userVisitList.getId());
            if(returnVisit == null){
                response.setResultCodeAndMessage("-1","该随访明细不存在!");
                return response;
            }
            //查询医生患者信息 开始
            UserVisit userVisit = new UserVisit();
            userVisit.setId(returnVisit.getVisitId());
            List<UserVisit> userVisits = userVisitDao.queryUserVisitList(userVisit);
            UserVisit uv = userVisits.get(0);
            uv.setUserVisitLists(null);
            //查询医生患者信息 结束  移除多余信息
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userVisit",returnVisit);
            jsonObject.put("user",uv);
            response.setResultCodeAndMessageAndResult("0","查询随访明细成功!",JsonUtils.toJsonString(jsonObject));
        }catch (Exception e){
            logger.error("查询随访明细异常!",e);
            response.setResultCodeAndMessage("-1","查询随访明细异常!");
        }
        return  response;
    }

    /***
     * 推送患者随访计划
     * yyt.bone.user.visit.msg.send
     * @param data
     * @return
     */
    public Response sendUserVisitMsg(String data){
        logger.info("推送患者随访计划,请求sendBoneMsgUserVisit入参:"+data);
        Response response = new Response();
        try {
            UserVisitList userVisitList = JsonUtils.parseObject(data,UserVisitList.class);
            UserVisit userVisit = userVisitDao.selectById(userVisitList.getVisitId());
            String firstMsg = userVisit.getUserName()+"，您好，"+userVisit.getDoctorName()+"医生向您发起诊后随访，将定期向您了解身体状况、给您发送疾病知识、提醒您复诊，点击查看详情。";
            String actionUrl = BoneMsgUtils.queryActionUrl(USER_VISIT_TEMPLATECODE)  + USER_VISIT_APP_CODE+"&id="+userVisitList.getId();
            String personalOpenId = userVisit.getPersonalOpenId();
            String contentDetail =""; //推送详情 长度大于20 省略后面的内容
            if(userVisitList.getContentDetail().length()>20){
                contentDetail=userVisitList.getContentDetail().substring(0,20)+"......";
            }else {
                contentDetail=userVisitList.getContentDetail();
            }
            String templateCode ="33001";
            //修改时间格式
            String visitTime = simpleDateFormat.format(simpleDateFormat.parse(userVisitList.getVisitTime()));
            String messageContentDoctor ="{\"user_type\":\"2\",\"platform_type\":\"" + 1 + "\",\"org_app_code\":\"" + USER_VISIT_APP_CODE +  "\",\"org_code\":\"rykj\",\"to_user\":\""
                    + personalOpenId
                    + "\",\"template_code\":\"" + templateCode
                    + "\",\"url\":\"" + actionUrl
                    + "\",\"msg_content\":\"{\\\"first\\\": \\\"" +
                    firstMsg +
                    "\\\"," +
                    "\\\"keyword1\\\": \\\""
                    + visitTime
                    + "\\\",\\\"keyword2\\\": \\\""
                    + userVisitList.getContent()
                    + "\\\",\\\"remark\\\": \\\"" +
                    contentDetail
                    + "\\\"}\"}";
            String method = "yyt.message.msg.template.send";

            logger.info("推送患者随访计划[BoneMsgServiceImpl.sendBoneMsgUserVisit发送消息模板入参] " + messageContentDoctor);
            Response messageRep = MessageService.callHumpFromInternal(method, messageContentDoctor);
            logger.info("推送患者随访计划[BoneMsgServiceImpl.sendBoneMsgUserVisit发送消息模板出参数] " + JsonUtils.toJsonString(messageRep));
            if ("0".equals(messageRep.getResultCode()) ){
                logger.info("sendBoneMsgUserVisit  推送患者随访计划成功");
                SimpleDateFormat simpleDateFormat  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //推送成功  更新随访计划状态
                userVisitList.setStatus((double) 1); //已发送
                userVisitList.setUpdateTime(simpleDateFormat.format(new Date()));
                userVisitListDao.update(userVisitList);
                logger.info("随访记录明细更新成功!"+JsonUtils.toJsonString(userVisitList));
                //查询该组随访是否已经全部推送完成
//                boolean flag =true;
                UserVisitList uvl = new UserVisitList();
                uvl.setVisitId(userVisitList.getVisitId());
                uvl.setStatus((double) 0);
                List<UserVisitList> userVisitLists = userVisitListDao.select(uvl);
//                for(UserVisitList entity:userVisitLists){
//                    if(entity.getStatus()==0){
//                        flag=false;
//                        break;
//                    }
//                }
                //全部已推送完成  则更新随访状态
                if(userVisitLists.isEmpty()){
                    userVisit.setStatus((short) 1); //1:已完成
                    userVisit.setUpdateTime(simpleDateFormat.format(new Date()));
                    userVisitDao.update(userVisit);
                    logger.info("更新随访状态为已完成!"+JsonUtils.toJsonString(userVisit));
                }else {
                    userVisit.setUpdateTime(simpleDateFormat.format(new Date()));
                    userVisitDao.update(userVisit);
                }
                response.setResultCodeAndMessage("0","推送患者随访计划成功");
            }else {
                response.setResultCodeAndMessage("1001","推送患者随访计划失败");
                logger.info("sendBoneMsgUserVisit  推送患者随访计划失败");
            }
        }catch (Exception e){
            logger.error("推送患者随访计划异常!",e);
            response.setResultCodeAndMessage("-1","推送患者随访计划异常!");
        }
        return response;
    }
}
